package com.jack.leetcode.每日一题;

import java.util.ArrayList;
import java.util.List;

/***
 * @author zhangjie
 * @date 2020/5/13 21:16
 */
public class 二叉树的层序遍历 {

    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int x) {
            val = x;
        }
    }

    public static List<List<Integer>> levelOrder(TreeNode root) {
        if (root == null) {
            return new ArrayList<>();
        }
        List<List<Integer>> result = new ArrayList<>();
        result.add(new ArrayList<>());
        int i = 0;
        read(result,root,i);
        return result;
    }

    private static void read(List<List<Integer>> result, TreeNode root, int i) {
        if (root == null) {
            return;
        }
        List<Integer> iLevel;
        if(i >= result.size()){
            iLevel = new ArrayList<>();
            result.add(iLevel);
        }else{
            iLevel = result.get(i);
        }
        iLevel.add(root.val);
        i++;
        read(result, root.left, i);
        read(result, root.right, i);
    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode(3);
        root.left = new TreeNode(9);
        root.right = new TreeNode(20);
        root.right.left = new TreeNode(15);
        root.right.right = new TreeNode(7);
        levelOrder(root);
    }
}
